import router from '@/router'
import { useUserStore } from '@/stores'
import axios from 'axios'
const service = axios.create({
  baseURL: '/admin',
  timeout: 5000 // request timeout
})
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const store = useUserStore()
    if (store.user?.token && config.headers) {
      config.headers.token = store.user.token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    if (error.response && error.response.status === 401) {
      router.push('/login')
      const store = useUserStore()
      store.setUser(null)
    }
    return Promise.reject(error)
  }
)

export default service
